package com.joe.blockview.utils;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.joe.blockview.model.Oprate;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class PlainUtils {
    /**
     * 保存方案
     *
     * @param oprates
     */
    public static void savePlain(Context context, String fielName, List<List<Oprate>> oprates) {
        try {
            FileOutputStream fileOutputStream = context.openFileOutput(fielName + ".json", MODE_PRIVATE);
            Gson gson = new Gson();
            String js = gson.toJson(oprates);
            fileOutputStream.write(js.getBytes("utf-8"));
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取方案
     *
     * @return
     */
    public static List<List<Oprate>> getPlain(Context context, String fileName) {
        List<List<Oprate>> oprates = null;
        try {
            FileInputStream fileInputStream = context.openFileInput(fileName + ".json");
            String str = "";
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fileInputStream.read(bytes)) != -1) {
                str = str + new String(bytes, 0, length);
            }
            fileInputStream.close();
            Gson gson = new Gson();
            oprates = gson.fromJson(str, new TypeToken<List<List<Oprate>>>() {
            }.getType());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return oprates;
    }
}
